<template>
  <div class="con-config">
    <p class="title">已选配置：</p>
    <div class="con_con">
      <div v-for="(item, index) in fromList" :key="index" class="sum">
        <div class="left">{{ item.title }}</div>
        <div class="right">{{ item.con }}</div>
      </div>
    </div>
    <div class="foot">
      <p class="costNum">费用总计：</p>
      <div style="margin-bottom: 10px">
        <span style="font-size: 20px; color: #ff3939; font-weight: 600">¥{{ price || 0 }}</span>
        <span style="font-size: 14px; color: #ff3939; margin: 0 50px 0 3px">元</span>
        <span style="font-size: 14px; color: #4098ff">目前8折</span>
      </div>
      <p style="font-size: 12px; color: #b2b2b2">
        实际消费以使用情况为准，可能低于此价格，此数据仅供参考
      </p>
      <el-button type="primary" style="width: 126px; height: 40px; margin-top: 10px" @click="handlePay">
        加入购物车
      </el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import Bus from "@/utils/bus";
import { onMounted, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { shoppingCar } from "@/api/cloud/index";
import { useRouter } from "vue-router";
import { localCache } from "@/utils/cache";
const router = useRouter();
const totalArea = ref('华东-上海一');
const fromList = ref<any>();
const resource_spec = ref();
const version = ref();
const surePassWord = ref();
const name = ref();
const passWord = ref();
const daiKuanNum = ref(5);
const stytemNum = ref(40);
const data_volume = ref<any>([]);
const nums = ref(1);
const a = ref(false);
const stytemValue = ref('GPSSD');
const regionId = ref();
const timeSpecificationValue = ref<any>(['2','1']);
const getInfos = ref<any>({});
fromList.value = [
  { title: "地域", con: "" },
  { title: "可用区域", con: "" },
  { title: "镜像", con: "" },
  { title: "系统盘", con: "" },
  { title: "数据盘", con: "" },
  { title: "带宽", con: "" },
  { title: "购买时长", con: "" },
  { title: "购买数量", con: "" },
];
onMounted(() => {
  fromList.value[0].con = "华东-上海一";
  fromList.value[1].con = "随机分配";
  fromList.value[2].con = "";
  fromList.value[3].con = "通用型SSD";
  fromList.value[4].con = "无";
  fromList.value[5].con = "1";
  fromList.value[6].con = "1年";
  fromList.value[7].con = "1";
  getInfos.value = localCache.getCache("myInformationAll");
});
Bus.on("daiKuanNum", (data: any) => {
  daiKuanNum.value = data;
  fromList.value[5].con = daiKuanNum.value;
});
Bus.on("stytemNum", (data: any) => {
  stytemNum.value = data;
});
Bus.on("totalArea", (data: any) => {
  totalArea.value = data;
  fromList.value[0].con = totalArea.value;
});
Bus.on("availableAreas", (data: any) => {
  fromList.value[1].con = data;
});
Bus.on("regionId", (data: any) => {
  regionId.value = data;
});
Bus.on("selectStym", (data: any) => {
  resource_spec.value = data;

  fromList.value[2].con = resource_spec.value;
});
Bus.on("stytemValueChange", (data: any) => {
  stytemValue.value = data;
  fromList.value[3].con = getType(stytemValue.value);
});
Bus.on("__os_version", (data: any) => {
  version.value = data.id;
});
Bus.on("num", (data: any) => {
  nums.value = data;
  fromList.value[7].con = nums.value;
});
Bus.on("stytemValue", (data: any) => {
  stytemValue.value = data;
});
Bus.on("data_volume", (data: any) => {
  if (data.length) {
    data_volume.value = data;
    fromList.value[4].con = getDataDiskType(data_volume.value);
  } else {
    data_volume.value = [];
    fromList.value[4].con = '无';
  }
});
const price = ref();
Bus.on("price", (data: any) => {
  price.value = data;
});
const priceKey = ref('');
Bus.on("priceKey", (data: any) => {
  priceKey.value = data;
});
const serivceName = ref('');
Bus.on("serivceName", (data: any) => {
  serivceName.value = data;
});
const network = ref('');//vcp
Bus.on("network", (data: any) => {
  network.value = data;
});
const nics = ref([]);//vcp
Bus.on("nics", (data: any) => {
  nics.value = data;
});
const iptype = ref('5_bgp');//iptype
Bus.on("iptype", (data: any) => {
  iptype.value = data;
});
const stytemOptions = ref([
  { label: "高IO", value: "SAS" },
  { label: "通用型SSD", value: "GPSSD" },
  { label: "超高IO", value: "SSD" },
  { label: "极速IO", value: "ESSD" },
]);
Bus.on("timeSpecificationValue", (data: any) => {
  timeSpecificationValue.value = data;
  fromList.value[6].con = timeSpecificationValue.value[0] == '2' ? timeSpecificationValue.value[1]+'个月' : timeSpecificationValue.value[1]+'年'
});

Bus.on("currentSpec", (data: any) => {
  name.value = data.name;
});
Bus.on("passWord", (data: any) => {
  passWord.value = data;
});
Bus.on("surePassWord", (data: any) => {
  surePassWord.value = data;
});
Bus.on("radio", (data: any) => {
  a.value = data;
});
const priceQueryJsonStr = ref('');
const fatherObj = defineProps({
  priceQueryJsonStr: {
    type: String,
    default: ''
  }
})

watch(
  () => fatherObj.priceQueryJsonStr,
  (value) => {
    priceQueryJsonStr.value = value;
  }, { immediate: true }
)

//转换系统盘格式
const getType = (e) => {
  let row = stytemOptions.value.find(item => item.value == e);
  return row ? row.label : '无'
}

//转换数据盘格式
const getDataDiskType = (arr: any[]) => {
  const data = <any>[]
  arr.forEach((item: any) => {
    if (item.diskType != '') {
      const label = stytemOptions.value.find((i: any) => i.value == item.diskType)?.label;
      data.push(label)
    }
  });
  return data.join()
}

// 反转字符串
const reverseString = (str: string) => {
    return str.split('').reverse().join('');
  }

// 加入购物车
const handlePay = () => {
  if (resource_spec.value === undefined) {
    ElMessage.warning("未选中镜像,请前往选择");
    return;
  }
  const regexp = new RegExp(/^[A-Za-z0-9_\-\u4e00-\u9fa5]{1,64}$/);
  if (stytemValue.value === undefined) {
    ElMessage.warning("系统盘类型不能为空");
    return;
  }
  if (serivceName.value == '') {
    ElMessage.warning("服务器名字不能为空");
    return;
  }
  if (!regexp.test(serivceName.value)) {
    ElMessage.warning("服务器名字不符合规范");
    return;
  }
  if (passWord.value === undefined) {
    ElMessage.warning("密码不能为空");
    return;
  }
  if (passWord.value.length < 8 || passWord.value.length > 26) {
    ElMessage.warning("密码长度为8-26位");
    return;
  }
  if (passWord.value.includes(getInfos.value.user.userName)) {
    ElMessage.warning("密码不能包含用户名");
    return
  }
  if (passWord.value.includes(reverseString(getInfos.value.user.userName))) {
    ElMessage.warning("密码不能包含用户名的逆序");
    return
  }
  let reg = /^(?![\da-z]+$)(?![\dA-Z]+$)(?![\d!@$%\^\_=+\[{}\]:,\./?~#*-]+$)(?![a-zA-Z]+$)(?![a-z!@$%\^\_=+\[{}\]:,\./?~#*-]+$)(?![A-Z!@$%\^\_=+\[{}\]:,\./?~#*-]+$)[\da-zA-z!@$%\^\_=+\[{}\]:,\./?~#*-]{8,26}$/;
  if (!reg.test(passWord.value)) {
    ElMessage.warning("密码只能包含大写字母、小写字母、数字和特殊字符(!@$%^-_=+[{}]:,./?~#*)且至少包含四种字符中的三种");
    return;
  }
  if (passWord.value.includes('root') || reverseString(passWord.value).includes('root')) {
    ElMessage.warning("密码不能包含用户名或者用户名的逆序");
    return;
  }
  if (surePassWord.value !== passWord.value) {
    ElMessage.warning("两次密码不一样，请重新输入");
    return;
  }
  ElMessageBox.confirm("是否确定加入购物车？", "加入购物车", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let dataDisk = '';
      data_volume.value?.forEach(item => {
        if (item.diskType != '') {
          dataDisk += `${item.diskType}数据盘${item.size}G;`
        }
      });
      let orderAbstract = `华为云购买【${(totalArea.value || '') + (name.value || '')}.Linux(${daiKuanNum.value || 0
        }M带宽;${stytemValue.value}系统盘${stytemNum.value || 0}G;${dataDisk ? dataDisk : "无数据盘"})】${timeSpecificationValue.value[1]
        }${timeSpecificationValue.value[0] == 2 ? "月" : "年"}x${nums.value}台`;
      let json = {
        count: nums.value,
        imageRef: version.value,
        flavorRef: name.value,
        name: serivceName.value,
        adminPass: passWord.value,
        publicip: {
          eip: {
            iptype: iptype.value,
            bandwidth: {
              size: daiKuanNum.value,
              sharetype: "PER",
            },
          },
        },
        isAutoRename: false,
        root_volume: {
          volumetype: stytemValue.value,
          size: stytemNum.value,
        },
        vpcid: network.value ,
        nics: nics.value.filter((item: any) => item.subnet_id),
        data_volume: data_volume.value.map((item: any) => {
          return {
            volumetype: item.diskType,
            size: item.size
          }
        }),
        extendparam: {
          "isAutoPay": "true",
          periodType: timeSpecificationValue.value[0] == 2 ? 'month' : 'year',
          periodNum: timeSpecificationValue.value[1] - 0,
          isAutoRenew: a.value + '',
        },
      };
      let data = {
        originalPrice: price.value,
        shoppingCarEnums: "CLOUD_SERVER",
        relationId: "",
        autoRenew: a.value,
        periodNum: nums.value,
        periodType: timeSpecificationValue.value[0] == 2 ? 30 : 365,
        orderAbstract,
        jsonStr: JSON.stringify(json),
        priceQueryJsonStr:priceQueryJsonStr.value,
        priceKey: priceKey.value,
        regionId: regionId.value
      }; 
      shoppingCar(data).then(() => {
        ElMessage.success("加入购物车成功,请前往控制台查看");
        router.push("/control/order/myShoppingCart");
      });
    })
    .catch(() => { });
};
</script>
<style lang="less" scoped>
.con-config {
  position: absolute;
  top: 0;
  right: -370px;
  width: 360px;
  height: 620px;
  background: #f5f7fa;
  box-shadow: -5px 5px 20px 0px #e3e8f0;
  border: 2px solid #ffffff;
  padding: 20px;
  z-index: 9;
  .title {
    font-size: 16px;
    font-weight: 600;
    display: block;
    width: 100%;
    height: 40px;
  }
  .con_con {
    width: 100%;
    height: 370px;
    padding: 20px 0 30px;
    border-top: 1px solid rgba(227, 232, 240, 0.5);
    border-bottom: 1px solid rgba(227, 232, 240, 0.5);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .sum {
      width: 100%;
      display: flex;
      .left {
        flex: 1;
        color: #909090;
      }
      .right {
        flex: 1;
      }
    }
  }
  .costNum {
    width: 100%;
    font-size: 16px;
    color: #909090;
    font-weight: 600;
    margin: 20px 0 10px;
  }
}
</style>
